import { Component, OnDestroy, OnInit } from '@angular/core';
import {
  EzFormConfiguration,
  EzFormValidators,
  EzInputConfiguration,
  EzRadioConfiguration,
  EzNumberConfiguration,
  EzCascaderConfiguration,
  EzSelectConfiguration,
  EzSelect,
  EzTextareaConfiguration,
  EzDatepickerConfiguration,
  EzCheckboxConfiguration,
  EzSwitchConfiguration,
} from 'ng-easy-form-lib';
import { timer } from 'rxjs';
import { take, tap, map } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'ez-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less'],
})
export class RegisterComponent implements OnInit, OnDestroy {
  username: EzInputConfiguration = {
    type: 'input',
    name: 'username',
    label: '用户名',
    placeholder: '请输入用户名',
    required: true,
    maxlength: 20,
    validators: [EzFormValidators.required, EzFormValidators.minlength(6, `用户必须不低于6个字符`)],
  };

  password: EzInputConfiguration = {
    type: 'input',
    name: 'password',
    label: '密码',
    placeholder: '请输入密码',
    required: true,
    maxlength: 20,
    password: true,
    validators: [EzFormValidators.required, EzFormValidators.minlength(6, '密码长度不低于6')],
    onChange: (control, group) => {
      group.get('confirmPassword').setValue(null);
    },
  };

  confirmPassword: EzInputConfiguration = {
    type: 'input',
    name: 'confirmPassword',
    label: '确认密码',
    placeholder: '请再次输入密码',
    required: true,
    maxlength: 20,
    password: true,
    validators: [
      EzFormValidators.required,
      (control, group) => {
        const passwd = group.get('password').getValue();
        if (passwd && passwd !== control.getValue()) {
          return { invalid: '两次密码输入不一致' };
        }
        return null;
      },
    ],
  };

  sex: EzRadioConfiguration = {
    type: 'radio',
    name: 'sex',
    label: '性别',
    options: [
      { label: '男', value: 'male' },
      { label: '女', value: 'female' },
    ],
  };

  age: EzNumberConfiguration = {
    type: 'number',
    name: 'age',
    label: '年龄',
    placeholder: '请输入年龄',
    max: 120,
    min: 0,
    formatter: value => (value || value === 0 ? `${value}岁` : null),
  };

  birthday: EzDatepickerConfiguration = {
    type: 'datepicker',
    name: 'birthday',
    label: '出生日期',
    format: 'yyyy/MM/dd',
    placeholder: '请选择出生日期',
    disabledDate: date => date > new Date(),
  };

  hobbies: EzCheckboxConfiguration = {
    type: 'checkbox',
    name: 'hobbies',
    label: '爱好',
    required: true,
    validators: [EzFormValidators.required],
    options: [
      {
        label: '看书',
        value: 'reading',
      },
      {
        label: '电影',
        value: 'movie',
      },
      {
        label: '运动',
        value: 'sport',
      },
    ],
  };

  useOptional: EzSwitchConfiguration = {
    type: 'switch',
    name: 'useOptional',
    label: '添加额外信息',
    value: false,
    onChange: (control, group, form) => {
      if (control.getValue()) {
        form.addGroup(
          {
            title: '额外信息',
            name: 'extraInfo',
            controls: [this.hobbies],
          },
          1
        );
      } else {
        form.removeGroup('extraInfo');
      }
    },
  };

  city: EzCascaderConfiguration = {
    type: 'cascader',
    name: 'city',
    label: '居住地',
    required: true,
    validators: [EzFormValidators.required],
    options: [
      {
        label: '江苏省',
        value: 'js',
        children: [
          {
            label: '南京市',
            value: 'nj',
            isLeaf: true,
          },
          {
            label: '扬州市',
            value: 'yz',
            isLeaf: true,
          },
        ],
      },
      {
        label: '浙江省',
        value: 'zj',
        children: [
          {
            label: '杭州市',
            value: 'hz',
            isLeaf: true,
          },
        ],
      },
    ],
    onChange: (control, group) => {
      group.get('region').setValue(null);
      const c = control.getValue();
      const regions = [];
      if (c && c[c.length - 1] === 'nj') {
        regions.push(
          {
            label: '玄武区',
            value: 'xwq',
          },
          { label: '浦口区', value: 'pkq' }
        );
      } else if (c && c[c.length - 1] === 'yz') {
        regions.push(
          {
            label: '广陵区',
            value: 'glq',
          },
          { label: '邗江区', value: 'hjq' }
        );
      } else if (c && c[c.length - 1] === 'hz') {
        regions.push({
          label: '滨江区',
          value: 'bjq',
        });
      }
      (group.get('region') as EzSelect).setOptions(
        timer(2000)
          .pipe(take(1))
          .pipe(map(() => regions))
      );
    },
  };

  region: EzSelectConfiguration = {
    type: 'select',
    name: 'region',
    label: '区/县',
    placeholder: '请选择具体区/县',
    required: true,
    validators: [EzFormValidators.required],
    options: [],
  };

  detailAddress: EzTextareaConfiguration = {
    type: 'textarea',
    name: 'address',
    label: '详细地址',
    autoSize: { minRows: 3, maxRows: 6 },
    maxlength: 1200,
  };

  email: EzInputConfiguration = {
    type: 'input',
    name: 'email',
    label: '邮箱',
    placeholder: '请输入邮箱',
    validators: [EzFormValidators.email()],
  };

  phone: EzInputConfiguration = {
    type: 'input',
    name: 'phone',
    label: '手机号',
    placeholder: '请输入手机号',
    validators: [EzFormValidators.phoneNumber()],
  };

  config: EzFormConfiguration = {
    cols: 1,
    submitButtonText: '注册',
    groupStyle: 'tab',
    groups: [
      {
        title: '基本信息',
        name: 'basicInfo',
        controls: [
          this.username,
          this.password,
          this.confirmPassword,
          this.sex,
          this.age,
          this.birthday,
          this.useOptional,
        ],
      },
      {
        title: '联系方式',
        name: 'contactInfo',
        controls: [this.city, this.region, this.detailAddress, this.email, this.phone],
      },
    ],
    onSubmit: form => {
      return timer(2000)
        .pipe(take(1))
        .pipe(tap(() => this.message$.success(`注册成功`)));
    },
  };

  constructor(private message$: NzMessageService) {}

  ngOnInit(): void {}
  ngOnDestroy(): void {}
}
